package com.jzy.message.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jzy.message.R;
import com.jzy.message.activities.adapter.QunliaoAdapter;
import com.jzy.message.activities.adapter.addpopleAdapter;
import com.jzy.message.activities.base.AppConfig;
import com.jzy.message.activities.base.BaseApplication;
import com.jzy.message.activities.bean.PostMessateBean;
import com.jzy.message.activities.bean.ReturnStatusResultEntity;
import com.jzy.message.activities.bean.addBean;
import com.jzy.message.activities.bean.getMessegeBean;
import com.jzy.message.control.view.DropdownListView;
import com.jzy.message.db.ChatMsgDao;
import com.jzy.message.db.SessionDao;
import com.jzy.message.entity.xmpp.Msg;
import com.jzy.message.entity.xmpp.Session;
import com.jzy.message.util.common.CommUtility;
import com.jzy.message.util.file.FileUtils;

import com.jzy.message.util.xmpp.Const;
import com.jzy.message.util.xmpp.PreferencesUtils;
import com.jzy.message.util.xmpp.XmppUtil;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.muc.MultiUserChat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 聊天界面
 * @author 白玉梁
 * @blog http://blog.csdn.net/baiyuliang2013
 * @weibo http://weibo.com/274433520
 * 
 * */
@SuppressLint("SimpleDateFormat")
public class QunliaoChatActivity extends Activity implements OnClickListener {
	private QunliaoChatActivity thisChatActivity;
	private ViewPager mViewPager;
	private LinearLayout mDotsLayout;
	private EditText input;
	private TextView send;
	private DropdownListView mListView;
	private QunliaoAdapter mLvAdapter;
	private ChatMsgDao msgDao;//读取数据库操作
	private SessionDao sessionDao;
	private LinearLayout chat_face_container;
	private ImageView iv_common_back;//返回图标
	private TextView tv_title;//图片
	//消息
	private List<Msg> listMsg;
	private SimpleDateFormat sd;
	private NewMsgReciver newMsgReciver;
	private MsgOperReciver msgOperReciver;
	private LayoutInflater inflater;
	private int offset;
	private String I,YOU;//为了好区分，I就是自己，YOU就是对方
	public MultiUserChat muc1;
	private String avatar;
	private  String hynicheng;
	private String bak3;//发送者的头像
	private String bak4;//发送者的昵称
	private ImageView img_chengyuan;
	private int userid;
	private int fromid;
	private String RealName;
	private String inputtext;
	private PostMessateBean postMessateBean;
	private addBean bean;
	private getMessegeBean getmessegeBean;
	public static final int POST_MESSEGE = 0x0004; //上传 自己发送的消息
	public static final int GET_MESSEGE = 0x0003; //获取 群聊消息
	private Handler mhandler = new Handler() {
		@Override
		public void handleMessage(final Message message) {
			switch (message.what) {
				case POST_MESSEGE:
					String url= AppConfig.JASON_SERVICE_URL+"qlxroomuserrelation/saveRoomMessage";
					AppConfig.getInst().postHttpRequestJsonClass(url, "1111",postMessateBean, addBean.class, new AppConfig.Callback() {
						@Override
						public void onSuccess(Object o) {

							Log.d("QunliaoChatActivity", "onFailure: "+o);
						}

						@Override
						public void onFailure(ReturnStatusResultEntity error) {
							Log.d("QunliaoChatActivity", "onFailure: "+error);
						}
					});
					break;
				case GET_MESSEGE:
					String url1= AppConfig.JASON_SERVICE_URL+"qlxroomuserrelation/queryListRoomMessage?roomId="+fromid;
					AppConfig.getInst().getHttpRequestJsonClass(url1, "1111", getMessegeBean.class, new AppConfig.Callback() {
						@Override
						public void onSuccess(Object o) {
							getmessegeBean=(getMessegeBean)o;
							listMsg=new ArrayList<>();
							//组装 数据
							if (getmessegeBean.getStatus()==1){

								if(getmessegeBean.getData()!=null||getmessegeBean.getData().size()>2){
									Log.d("QunliaoChatActivity123", "onSuccess: "+getmessegeBean.getData().toString());
									for (int i=getmessegeBean.getData().size()-1; i>=0;i--){
                                        Msg msg=new Msg();
                                        if (getmessegeBean.getData().get(i).getUserId()==userid){
											msg.setContent(getmessegeBean.getData().get(i).getUserName()+"#@#"+getmessegeBean.getData().get(i).getContent());
										}else {
											msg.setContent(getmessegeBean.getData().get(i).getPhone()+"#@#"+getmessegeBean.getData().get(i).getUserName()+"#@#"+getmessegeBean.getData().get(i).getContent());
										}

										msg.setType("chat");
										msg.setFromUser(YOU);
										if (getmessegeBean.getData().get(i).getUserId()==userid){
											msg.setIsComing(1);
										}else {
											msg.setIsComing(0);
										}
										msg.setToUser(avatar);
										msg.setMsgId(i);
										listMsg.add(msg);
									}
									offset=0;
									/*listMsg=msgDao.queryMsg(YOU,I,offset);*/
									offset=listMsg.size();
									mLvAdapter = new QunliaoAdapter(getApplicationContext(), listMsg,avatar);
									mListView.setAdapter(mLvAdapter);
									mListView.setSelection(listMsg.size());
								}

							}else {
								offset=0;
								listMsg=msgDao.queryMsg(YOU,I,offset);
								offset=listMsg.size();
								mLvAdapter = new QunliaoAdapter(getApplicationContext(), listMsg,avatar);
								mListView.setAdapter(mLvAdapter);
								mListView.setSelection(listMsg.size());
							}
						}

						@Override
						public void onFailure(ReturnStatusResultEntity error) {
							Log.d("QunliaoChatActivity", "onFailure: "+error);
						}
					});
					break;
			}
		}
	};
	@SuppressLint("ShowToast")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.qunliao_message_main_chat);
		thisChatActivity=this;
		userid=getIntent().getIntExtra("userid",0);
		fromid=getIntent().getIntExtra("fromid",0);
		RealName=getIntent().getStringExtra("RealName");
		I= PreferencesUtils.getSharePreStr(this, "username");
		YOU=getIntent().getStringExtra("from");
		avatar=getIntent().getStringExtra("avatar");
		hynicheng=getIntent().getStringExtra("hynicheng");

		inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		tv_title=(TextView) findViewById(R.id.tv_common_title);

		tv_title.setText(YOU);
		iv_common_back=(ImageView)findViewById(R.id.iv_common_back);
		iv_common_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				thisChatActivity.finish();
			}
		});
		sd=new SimpleDateFormat("MM-dd HH:mm");
		msgDao=new ChatMsgDao(this);
		sessionDao=new SessionDao(this);//当前会话
		msgOperReciver=new MsgOperReciver(); //广播接收器
		newMsgReciver=new NewMsgReciver();//新消息
		IntentFilter intentFilter=new IntentFilter(Const.ACTION_MSG_OPER);
		registerReceiver(msgOperReciver, intentFilter);
		intentFilter=new IntentFilter(Const.ACTION_NEW_MSG);
		registerReceiver(newMsgReciver, intentFilter);
		//初始化控件
		initViews();
		//初始化数据
		initData();
		//进入群聊
		enterRoom(I,YOU);
	}
	/**
	 * 初始化控件
	 */
	private void initViews() {
		mListView = (DropdownListView) findViewById(R.id.message_chat_listview);
		//表情布局
		chat_face_container=(LinearLayout) findViewById(R.id.chat_face_container);
		mViewPager = (ViewPager) findViewById(R.id.face_viewpager);
		mViewPager.setOnPageChangeListener(new PageChange());
		//表情下小圆点
		mDotsLayout = (LinearLayout) findViewById(R.id.face_dots_container);
		input = (EditText) findViewById(R.id.input_sms);
		send = (TextView) findViewById(R.id.send_sms);
		img_chengyuan = (ImageView) findViewById(R.id.img_chengyuan);
		img_chengyuan.setVisibility(View.VISIBLE);
		//点击群成员
		img_chengyuan.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent=new Intent(QunliaoChatActivity.this,ChengyuanActivity.class);
				intent.putExtra("userid",userid);
				intent.putExtra("username",avatar);
				intent.putExtra("room",YOU);
				startActivity(intent);
			}
		});
		input.setOnClickListener(this);
		input.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				Log.d("dddddd", "s: "+s+"start:"+start+"count:"+count+"after:"+after);
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				Log.d("dddddd11", "s: "+s+"start:"+start+"before:"+before+"count:"+count);
				Log.i("a",String.valueOf(start)+"-"+String.valueOf(before)+"-"+String.valueOf(count));

				if(count>0)//添加文字
				{
					if(send.getVisibility()==View.GONE)
						setaddsendrelation(R.id.send_sms);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		// 发送
		send.setOnClickListener(this);
		
		//mListView.setOnRefreshListenerHead(this);
		mListView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				if(arg1.getAction()==MotionEvent.ACTION_DOWN){
					if(chat_face_container.getVisibility()==View.VISIBLE){
						chat_face_container.setVisibility(View.GONE);
					}
					hideSoftInputView();
				}
				return false;
			}
		});
	}
	//本地 数据库 获取记录 展示
	public void initData(){
		mhandler.sendEmptyMessage(GET_MESSEGE);
		/*offset=0;
		listMsg=msgDao.queryMsg(YOU,I,offset);
		offset=listMsg.size();
		mLvAdapter = new QunliaoAdapter(this, listMsg,avatar);
		mListView.setAdapter(mLvAdapter);
		mListView.setSelection(listMsg.size());*/
	}
	/*
	* 进入群聊
	* */
	private void  enterRoom(String I,String roomName)
	{
		this.muc1=XmppUtil.joinMultiUserChat(BaseApplication.xmppConnection, I,YOU,"");
		if(muc1==null)
		{

			CommUtility.showmsg(thisChatActivity,"进入房间失败");
			finish();
		}
		else {
			muc1.addMessageListener(new ChatMultiListener());//注册群组消息的监听，用于接收消息
		}
	}
	/**
	 */
	@Override
	protected void onStart() {
		super.onStart();
	}
	
	
	private void setaddsendrelation(int flag)
	{

		 if(flag== R.id.send_sms)//显示send
		{
				send.setVisibility(View.VISIBLE);
		}
	}
	@Override
	public void onClick(View arg0) {
		int id=arg0.getId();
		/*if(id==0){
			CommUtility.showmsg(thisChatActivity,"请务输入空格");
			return;
		}*/
		if(id== R.id.send_sms)
		{
			String content=hynicheng+"#@#"+input.getText().toString();
			inputtext=input.getText().toString();
			if(TextUtils.isEmpty(content)){
				return;
			}
			if("".equals(inputtext.trim())){
				CommUtility.showmsg(thisChatActivity,"不能发送空白信息");
				return;
			}
			sendMsgText(content);
		}
		else if(id== R.id.input_sms)
		{
			if(chat_face_container.getVisibility()==View.VISIBLE){
				chat_face_container.setVisibility(View.GONE);
			}
		}
	}
	
	/**
	 * 执行发送消息 文本类型
	 * @param content
	 */
	void sendMsgText(String content){
		Msg msg=getChatInfoTo(content, Const.MSG_TYPE_TEXT);
		msg.setMsgId(msgDao.insert(msg));
		listMsg.add(msg);
		offset=listMsg.size();
		mLvAdapter.notifyDataSetChanged();
		input.setText("");

		//发送消息体
		final org.jivesoftware.smack.packet.Message msg_send=new org.jivesoftware.smack.packet.Message();
		//msg_send.setTo(YOU);
		//msg_send.setFrom(I);
		msg_send.setBody(content);
		msg_send.setType(org.jivesoftware.smack.packet.Message.Type.groupchat);//发送消息体
		msg_send.setSubject(msg.getType());
		msg_send.setTo(muc1.getRoom());
		msg_send.setProperty("date",msg.getDate());
		//final String message=YOU+Const.SPLIT+I+Const.SPLIT+Const.MSG_TYPE_TEXT+Const.SPLIT+content+Const.SPLIT+sd.format(new Date());
		new Thread(new Runnable() {
			@Override
			public void run() {
				XmppUtil.sendMultiChatMsg(muc1, msg_send);
				//发送成功后 吧发送的内容 上传到接口
				postMessateBean=new PostMessateBean();
				postMessateBean.setContent(inputtext);
				postMessateBean.setRoomId(fromid);
				postMessateBean.setUserId(userid);
                postMessateBean.setPhone(avatar);
                postMessateBean.setUserName(RealName);
				mhandler.sendEmptyMessage(POST_MESSEGE);
				inputtext="";
			}
		}).start();
		updateSession(Const.MSG_TYPE_TEXT,content);
	}
	/**
	 * 发送的信息
	 *  from为收到的消息，to为自己发送的消息
	 * @param message => 接收者卍发送者卍消息类型卍消息内容卍发送时间
	 * @return
	 */
	private Msg getChatInfoTo(String message, String msgtype) {
		String time=sd.format(new Date());
		Msg msg = new Msg();
		msg.setFromUser(YOU);
		msg.setToUser(I);
		msg.setType(msgtype);
		msg.setIsComing(1);
		msg.setContent(message);
		msg.setDate(time);
		return msg;
	}
	
	void updateSession(String type,String content){
		Session session=new Session();
		session.setFrom(YOU);
		session.setTo(I);
		session.setNotReadCount("");//未读消息数量
		session.setContent(content);
		session.setTime(sd.format(new Date()));
		session.setType(type);
		if(sessionDao.isContent(YOU, I)){
			sessionDao.updateSession(session);
		}else{
			sessionDao.insertSession(session);
		}
		Intent intent=new Intent(Const.ACTION_ADDFRIEND);//发送广播，通知消息界面更新
		sendBroadcast(intent);
	}
	
	
	/**
	 * 表情页改变时，dots效果也要跟着改变
	 * */
	class PageChange implements OnPageChangeListener {
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}
		@Override
		public void onPageSelected(int arg0) {
			for (int i = 0; i < mDotsLayout.getChildCount(); i++) {
				mDotsLayout.getChildAt(i).setSelected(false);
			}
			mDotsLayout.getChildAt(arg0).setSelected(true);
		}
	}

	/**
	 * 下拉加载更多
	 */
	/*@Override
	public void onRefresh() {
		List<Msg> list=msgDao.queryMsg(YOU,I,offset);
		if(list.size()<=0){
			mListView.setSelection(0);
			mListView.onRefreshCompleteHeader();
			return;
		}
		listMsg.addAll(0,list);
		offset=listMsg.size();
		mListView.onRefreshCompleteHeader();
		mLvAdapter.notifyDataSetChanged();
		mListView.setSelection(list.size());
	}
	*/
	
	/**
	 * 隐藏软键盘
	 */
	public void hideSoftInputView() {
		InputMethodManager manager = ((InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE));
		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getCurrentFocus() != null)
				manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
	/**
	 * 接收消息记录操作广播：删除复制
	 * @author baiyuliang
	 */
	private class MsgOperReciver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			int type=intent.getIntExtra("type", 0);
			final int position=intent.getIntExtra("position", 0);
			if(listMsg.size()<=0){
				return;
			}
			final Msg msg=listMsg.get(position);
			switch (type) {
			case 1://聊天记录操作
				Builder bd = new Builder(QunliaoChatActivity.this);
				String[] items=null;
				if(msg.getType().equals(Const.MSG_TYPE_TEXT)){
					items =  new String[]{"删除记录","删除全部记录","复制文字"};
				}else if(msg.getType().equals(Const.MSG_TYPE_CONFERENCECALL)){
					items =  new String[]{"删除记录","删除全部记录","进入视频会议"};
				}else if(msg.getType().equals(Const.MSG_TYPE_VOICECALL)){
					items =  new String[]{"删除记录","删除全部记录","语音通话"};
				}
				else {
					items =  new String[]{"删除记录","删除全部记录"};
				}
				bd.setItems(items, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						switch (arg1) {
						case 0://删除
							listMsg.remove(position);
							offset=listMsg.size();
							mLvAdapter.notifyDataSetChanged();
							msgDao.deleteMsgById(msg.getMsgId());
							break;
						case 1://删除全部
							listMsg.removeAll(listMsg);
							offset=listMsg.size();
							mLvAdapter.notifyDataSetChanged();
							msgDao.deleteAllMsg(YOU, I);
							break;
						case 2://复制
							String msgcontent=msg.getContent();
							switch (msg.getType())
							{
								case Const.MSG_TYPE_CONFERENCECALL://视频会议
									//开启视频呼叫界面

									//Intent it_conference=new Intent(thisChatActivity, TelepresenceActivity.class);
									//it_conference.putExtra("CallNumber",msgcontent);
									//thisChatActivity.startActivity(it_conference);
									break;
								case Const.MSG_TYPE_VOICECALL://语音通话
									//开启语音呼叫界面
									//Intent it_voicecall=new Intent(thisChatActivity, CallActivity.class);
									//it_voicecall.putExtra("CallNumber",msgcontent);
									//thisChatActivity.startActivity(it_voicecall);
									//thisChatActivity.startActivity(new Intent(thisChatActivity, CallActivity.class).putExtra("CallNumber",msgcontent));
									break;
								default:
									ClipboardManager cmb = (ClipboardManager) QunliaoChatActivity.this.getSystemService(QunliaoChatActivity.CLIPBOARD_SERVICE);
									cmb.setText(msg.getContent());
									Toast.makeText(getApplicationContext(), "已复制到剪切板", Toast.LENGTH_SHORT).show();
									break;
							}
							break;
						}
					}
				});
				bd.show();
				break;
			}
				
			}
	}
	
	/**
	 * 接收消息记录操作广播：删除复制
	 * @author baiyuliang
	 */
	private class NewMsgReciver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String[] Paras=intent.getStringArrayExtra("Paras");
			//String subject=Paras[0];
			String body=Paras[1];
			String from=Paras[2];
			String a=from.split("/")[1];
			String b=a;
			if(a.contains("@"))
			{
				b=a.split("@")[0];
			}
			if(b.equals(I))
				return;
			String time=sd.format(new Date());
			Msg msg = new Msg();
			msg.setFromUser(b);
			msg.setToUser(I);
			msg.setType(Const.MSG_TYPE_TEXT);
			msg.setIsComing(0);//0代表别人发的  1为自己发的
			msg.setContent(b+"#@#"+body);
			msg.setDate(time);
			listMsg.add(msg);
			offset=listMsg.size();
			mLvAdapter.notifyDataSetChanged();
		}
	}

	/*
	* 群聊接收消息广播
	* */
	public class ChatMultiListener implements PacketListener {
		@Override
		public void processPacket(Packet packet) {
			org.jivesoftware.smack.packet.Message message = (org.jivesoftware.smack.packet.Message) packet;
			String time=sd.format(new Date());
			String msgBody = message.getBody();
			if (TextUtils.isEmpty(msgBody))
				return;
			String to=message.getTo().split("@")[0];//msgs[0];//接收者,当然是自己
			String from=message.getFrom().split("@")[0];//msgs[1];//发送者，谁给你发的消息
			String fromUserPhoneNo=message.getFrom().split("@")[1].split("/")[1];
			if(fromUserPhoneNo.equals(I))
				return;
			String msgtype= message.getSubject()==null?Const.MSG_TYPE_TEXT:message.getSubject();//msgs[2];//消息类型
			String msgcontent=msgBody;//msgs[3];//消息内容
			String nicheng=msgBody.split("#@#")[0];//好友的昵称
			String msgtime=time;//msgs[4];//消息时间
			/*bak4=nicheng;
			bak3= AppConfig.JASON_SERVICE_URL_TOUXIANG+"upload/"+fromUserPhoneNo+".jpg";//好友的头像
*/
			if(message.getProperty("date")!=null)
			{
				msgtime=(String)message.getProperty("date");
			}

			///保存群聊进来的消息
			Msg msg=new Msg();
			msg.setToUser(to);//代表我自己
			msg.setFromUser(from);//代表 群名字
			msg.setIsComing(0);
			msg.setContent(fromUserPhoneNo+"#@#"+msgcontent);//手机号#@#昵称#@#内容     的格式
			msg.setDate(msgtime);
			msg.setIsReaded("0");
			msg.setType(msgtype);
		/*	msg.setBak3(bak3);
			msg.setBak4(bak4);*/
			msgDao.insert(msg);

			//将接收的消息通过广播的形式发给界面，不能直接给界面赋值，没有操作界面的权限
			Intent intent=new Intent(Const.ACTION_NEW_MSG);//发送广播到聊天界面
			intent.putExtra("Paras",new String[]{message.getSubject()==null?Const.MSG_TYPE_TEXT:message.getSubject(),message.getBody(),message.getFrom()});
			thisChatActivity.sendBroadcast(intent);
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(muc1!=null){
			muc1.leave();
		}
		unregisterReceiver(msgOperReciver);
		unregisterReceiver(newMsgReciver);
	}
	
    @Override
    protected void onResume() {
 		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				//让输入框获取焦点
				input.requestFocus();
			}
		}, 100);
    	super.onResume();
    };
	
	/**
	 * 监听返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			 hideSoftInputView();
				if(chat_face_container.getVisibility()==View.VISIBLE){
					chat_face_container.setVisibility(View.GONE);
				}else{
					finish();
					muc1.leave();
				}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
